<?php
namespace app\admin\controller;
use think\Db;
use think\Request;
class Fapiao extends Base {
    public function index(){
        if(request()->isAjax()){
            extract(input());
            $map = [
                'fapiao_status' => ['>=',2]
            ];
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            if(isset($fapiao_type) && $fapiao_type)
            {
                $map['fapiao_type'] = $fapiao_type;
            }
            if(isset($contract) && $contract)
            {
                $map['order_contract'] = $contract;
            }
            if(isset($fapiao_status) && $fapiao_status)
            {
                $map['fapiao_status'] = $fapiao_status;
            }
            if(isset($n_title) && $n_title)
            {
                $map['school_name|user_phone|order_no'] = ['like',"%" . $n_title . "%"];
            }
            if(isset($start) && $start)
            {
                $map['fapiao_time'] = ['>= time',$start];
            }
            if(isset($end) && $end)
            {
                $map['fapiao_time'] = ['<= time',$end];
            }
            if(isset($start) && $start && isset($end) && $end)
            {
                $map['fapiao_time'] = ['between time',[$start,$end]];
            }
            $field = 'o.*,school_erp,school_name,user_username,user_phone';
            $count = Db::table('up_self_order')->alias('o')
                ->join('up_school s','o.order_school=s.school_erp','LEFT')
                ->join('up_u_user u','o.user_id=u.user_id','LEFT')
                ->where($map)
                ->count();// 获取总条数
            $lists = Db::table('up_self_order')->alias('o')
                ->join('up_school s','o.order_school=s.school_erp','LEFT')
                ->join('up_u_user u','o.user_id=u.user_id','LEFT')
                ->where($map)
                ->order('fapiao_status ASC')
                ->page($Nowpage,$limits)
                ->field($field)
                ->select();
            return json(['code'=>220,'msg'=>'','count'=>$count,'data'=>$lists]);
        }
        return $this->fetch();
    }

    /**
     * 无需开票
     */
    public function nokaipiao(){
        extract(input());
        $order_id = input('id');
        Db::table('up_self_order')->where('order_id', $order_id)->setField('fapiao_status',6);
        return json(['code' => 200,'msg' => '操作成功']);
    }
    /**
     * 修改
     */
    public function editFp(){
        extract(input());
        if(Request::instance()->isPost()){
            extract(input());
            $param  = [
                'fapiao_type'=>$fapiao_type,
                'fapiao_head'=>$fapiao_head,
                'fapiao_shui'=>$fapiao_shui,
                'fapiao_email'=>$fapiao_email,
                'fapiao_remark'=>$fapiao_remark
            ];
            if($fapiao_type == 1) $param['fapiao_shui'] = '';
            Db::table('up_self_order')
                ->where('order_id',$order_id)
                ->update($param);
            return json(['code'=>200,'msg'=>'修改成功']);
        }
        $order = Db::table('up_self_order')
            ->where('order_id',$order_id)
            ->find();
        return $this->fetch('fapiao/edit',['data'=>$order]);
    }
    /**
     * 开票
     * @return mixed
     */
    public function kaipiao(){
        error_reporting(0);
        $order_id = input('id');
        $today = date('Y-m-d H:i:s');
        $is_send = Db::table('up_self_order')->where('order_id', $order_id)->find();
        $user_id = $is_send['user_id'];
        $fapiao_type = $is_send['fapiao_type'];
        $fapiao_head = $is_send['fapiao_head'];
        $fapiao_shui = $is_send['fapiao_shui'];
        $fapiao_email = $is_send['fapiao_email'];
        $fapiao_remark = $is_send['fapiao_remark'];
        if ($is_send['fapiao_status'] != 2 && $is_send['fapiao_status'] != 5) {
            return json(['code' => 100, 'msg' => '只有待开票或需要重新开票的才可以开票']);
        }
        //
        $shouhou_habe = Db::table('up_self_order_detail')
            ->where('order_id', $order_id)
            ->where('th_status', '<>',0)
            ->where('refund_status', '<>',2)
            ->find();
        if ($shouhou_habe) {
            return json(['code' => 100, 'msg' => '此订单有进行中的售后，暂不能开票']);
        }
        $detailids = Db::table('up_self_order_detail')->where('order_id', $order_id)->column('detail_id');
        $detailids_no = Db::table('up_self_order_tui')
            ->where('order_detail_id', 'in',$detailids)
            ->where('type', 2)
            ->where('status', 'in','1,2')
            ->column('order_detail_id');
        $where = [
            'order_id' => $order_id
        ];
        if($detailids_no){
            $where['detail_id'] = ['not in',$detailids_no];
        }
        $details = Db::table('up_self_order_detail')
            ->where($where)
            ->field('detail_id,num,unit_price')
            ->select();
        if(empty($details)){
            return json(['code' => 100, 'msg' => '此订单已经售后，不能开票']);
        }
        $mingxiPrice = 0;
        foreach ($details as $k=>$v){
            $mingxiPrice += ($v['unit_price']*$v['num']);
        }
        if($is_send['express_original_price'] > 0){
            $mingxiPrice += $is_send['express_original_price'];
//            $mingxi[] = [
//                'goodsName' => '*运输服务*运费',
//                'num' => 1,
//                'price' => $is_send['express_original_price'],
//                'unit' => '-',
//                'withTaxFlag' => '1',
//                'taxRate' => '0.13'
//            ];
        }
        $mingxi = [
            'goodsName' => '学生校服',
            'withTaxFlag' => '1',
            'num' => 1,
            'price' => $mingxiPrice,
            'unit' => '套',
            'taxRate' => '0.13'
        ];
        //
        if($is_send['order_contract'] != 1){
            $sch = Db::table('up_school')->where('school_erp',$is_send['order_school'])
                ->field('school_head,school_shui')->find();
            if(empty($sch)){
                return json(['code' => 100, 'msg' => '学校信息有误，无法开票']);
            }
            if(empty($sch['school_head']) || empty($sch['school_shui'])){
                return json(['code' => 100, 'msg' => '学校信息不全，请稍后再开票']);
            }
            $fapiao = [
                'fapiao_status' => 1,
                'fapiao_type' => 2,
                'fapiao_head' => $fapiao_head,
                'fapiao_shui' => $fapiao_shui,
                'fapiao_email' => $fapiao_email,
                'fapiao_remark' => $fapiao_remark,
                'fapiao_time' => $today
            ];
        }else{
            $fapiao = [
                'fapiao_status' => 1,
                'fapiao_type' => $fapiao_type,
                'fapiao_head' => $fapiao_head,
                'fapiao_shui' => '',
                'fapiao_email' => $fapiao_email,
                'fapiao_remark' => $fapiao_remark,
                'fapiao_time' => $today
            ];
            if($fapiao_type == 2 ){
                $fapiao['fapiao_shui'] = $fapiao_shui;
            }
        }
        $user = Db::table('up_u_user')->where('user_id', $user_id)
            ->field('user_phone')->find();
        $nuonuoapi = new \app\api\controller\Base();
        $res = $nuonuoapi->askFapiaoNew($fapiao['fapiao_head'],$fapiao['fapiao_shui'],$user['user_phone'],$fapiao_email,$mingxi,$is_send['order_no'],$fapiao_remark);
        if($res['status'] == 200){
            $fapiao['fapiao_ordernum'] = $res['msg'];
            Db::table('up_self_order')
                ->where('order_id', $order_id)
                ->update([
                    'fapiao_ordernum' => $res['msg'],
                    'fapiao_status' => 3,
                    'deleted_at' => $today
                ]);
//            try{
//                $cxres = $nuonuoapi->nuonuoCx($res['msg']);
//                if($cxres['status'] == 200){
//                    if($cxres['msg']['status'] == 2){
//                        Db::table('up_self_order')
//                            ->where('order_id', $order_id)
//                            ->update([
//                                'fapiao_image' => $cxres['msg']['pictureUrl'],
//                                'fapiao_status' => 4
//                            ]);
//                    }elseif ($cxres['msg']['status'] == 22 || $cxres['msg']['status'] == 24){
//                        Db::table('up_self_order')
//                            ->where('order_id', $order_id)
//                            ->update([
//                                'fapiao_status' => 5
//                            ]);
//                    }
//                }
//            }catch(\Exception $e){}
            return json(['code' => 200,'msg' => '操作成功']);
        }else{
            return json(['code' => 100,'msg' => $res['msg']]);
        }
    }

    /**
     * 查询重开
     * @return \think\response\Json
     */
    public function fapiaoInfo(){
        $order_id = input('id');
        $today = date('Y-m-d H:i:s');
        $is_send = Db::table('up_self_order')->where('order_id', $order_id)->find();
        if(!$is_send['fapiao_ordernum']) return json(['code' => 100,'msg' => '请先开发票']);
        if($is_send['fapiao_status'] == 4 || $is_send['fapiao_status'] == 5 || $is_send['fapiao_status'] == 6) return json(['code' => 200,'msg' => '无需查询']);
        $nuonuoapi = new \app\api\controller\Base();
        $cxres = $nuonuoapi->nuonuoCx($is_send['fapiao_ordernum']);
        if($cxres['status'] == 200){
            if($cxres['msg']['status'] == 2){
                Db::table('up_self_order')
                    ->where('order_id', $order_id)
                    ->update([
                        'fapiao_image' => $cxres['msg']['pictureUrl'],
                        'fapiao_status' => 4
                    ]);
                return json(['code' => 200,'msg' => '开票成功']);
            }elseif ($cxres['msg']['status'] == 22 || $cxres['msg']['status'] == 24){
                Db::table('up_self_order')
                    ->where('order_id', $order_id)
                    ->update([
                        'fapiao_status' => 5
                    ]);
                return json(['code' => 200,'msg' => '开票失败：' . $cxres['msg']['failCause']]);
            }else{
                return json(['code' => 200,'msg' => $cxres['msg']['statusMsg']]);
            }
        }
        return json(['code' => 100,'msg' => '查询失败']);
    }
}